<template>
  <aside>
    <ul ref="el">
      <li v-for="(todo, idx) in todos" :key="todo.id" @click="toggle('click', idx, $event)">
        <i class="iconfont icon-suoding"></i>
        <input type="text" v-model="todos[idx].name" :disabled="!todo.isEdit"
               @keyup.enter="toggle('keyup',idx)" @blur="toggle('blur', idx)">
        <span>1</span>
      </li>
      <li @click="addTodo">
        <i class="iconfont icon-jiahao"></i><span>新增</span>
      </li>
    </ul>
  </aside>
</template>

<script>
import {
  defineComponent,
  ref,
  reactive,
  nextTick,
  onMounted,
  onUnmounted,
  watch,


} from 'vue'
  import {useRouter} from 'vue-router'
  import {nanoid} from 'nanoid'


  export default  defineComponent({
    name: 'Menu',
    setup(props, ctx){
      const router = useRouter()

      const todoIndex = ref(0)
      const el = ref(null)
      const todos = reactive([])

      function addTodo(){
        todos.push({name:'newList', id:nanoid(), isEdit:false})
        nextTick(()=>{
          el.value.children.length? el.value.children[0].style.color = 'red':''
        })

      }

      function toggle(type, idx, ev){
        todos[idx].isEdit = type==='click'

        if(type==='click'){
          nextTick(()=>{
            ev.target.focus()
          })

          router.push(`/${todos[idx].id}`)

          todos[idx].name = ''
        }


      }

      onMounted(()=>{
        window.addEventListener('keyup', (ev)=>{
          if(ev.key === 'ArrowUp' ){
            todoIndex.value--
            ;[...el.value.children].forEach((ch,idx)=>{
              if(idx===todoIndex.value)
                ch.style.color = 'red'
              else
                ch.style.color = 'black'
            })

          }

          if(ev.key === 'ArrowDown'){
            todoIndex.value++

            ;[...el.value.children].forEach((ch,idx)=>{
              if(idx===todoIndex.value)
                ch.style.color = 'red'
              else
                ch.style.color = 'black'
            })
          }
        })
      })

      watch(todoIndex, (newVal)=>console.log(newVal))


      return {
        todoIndex,
        todos,
        el,
        addTodo,
        toggle,

      }
    }
  })
</script>

<style lang="less" scoped>
  aside {
    width: 300px;
    float: left;
  }

  ul {
    list-style: none;
    margin: 0;
    padding: 0;
  }

  li {
    line-height: 42px;
  }

</style>
